from common.recordlog import logs
from conf.operationConfig import OperationConfig
import pymysql

conf = OperationConfig()

class ConnectMysql:
    # 连续读取mysql数据库的数据

    def __init__(self):
        mysql_conf = {
            'host': conf.get_mysql_conf('host'),
            'port': int(conf.get_mysql_conf('port')),
            'user': conf.get_mysql_conf('username'),
            'password': conf.get_mysql_conf('password'),
            'database': conf.get_mysql_conf('database')
        }

        try:
            self.conn = pymysql.connect(**mysql_conf,charset='utf8')
            # cursor=pymysql.cursors.DictCursor:将数据库表字段显示，以key-value形式显示
            self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
            logs.info("""成功连接到MySQL数据库
            host:{host}
            port:{port}
            db:{database}
            """.format(**mysql_conf))
        except Exception as e:
            logs.error(e)

    def close(self):
        # 关闭数据库连接
        if self.conn and self.cursor:
            self.cursor.close()
            self.conn.close()


    def query(self,sql):
        # 查询数据
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            res = self.cursor.fetchall()
            return res
        except Exception as e:
            logs.error(e)
        finally:
            self.close()

    def insert(self,sql):
        # 新增数据
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            logs.info('新增数据成功')
        except Exception as e:
            logs.error(e)
        finally:
            self.close()

    def delete(self,sql):
        # 删除数据
        try:
            self.cursor.execute(sql)
            self.conn.commit()
            logs.info('删除成功')
        except Exception as e:
            logs.error(e)
        finally:
            self.close()

    def update(self,sql):
        # 更新数据
        try:
            self.cursor.execute(sql)
            self.conn.commit()  # 提交事务
            affected_rows = self.cursor.rowcount  # 获取受影响的行数
            logs.info(f'更新数据成功，受影响行数：{affected_rows}')
            return affected_rows  # 返回受影响行数，方便判断更新结果
        except Exception as e:
            logs.error(e)
        finally:
            self.close()  # 确保资源关闭

